#!/bin/bash

# 功能描述：用於更新CLI、HOME、INIT
rootDir=`dirname $(readlink -f "$0")`; headColor='\033[38;2;41;184;219m'; endColor='\033[0m'
cd $rootDir; echo cd `pwd`

#      ____     ____    ____           ______    ____     ___       ____     __       ______
#     / __ \   /  _/   / __ \         / ____/   / __ \   /   |     / __ \   / /      / ____/
#    / /_/_/   / /    / /_/ /        / / __    / /_/ /  / /| |    / / / /  / /      / __/   
#   / /_/\   _/ /    / ____/        / /_/ /   / _, _/  / ___ |   / /_/ /  / /___   / /___   
#  /_____/  /___/   /_/             \____/   /_/ |_|  /_/  |_|  /_____/  /_____/  /_____/  



# 一、更新脚手架
echo -n -e "${headColor}▶ 是否拉取脚手架【am】? (Y/n) ${endColor}"
read pullPage

if [ "$pullPage" == "Y" ] || [ "$pullPage" == "y" ]
then
        
    echo -e "${headColor}▶ 开始拉取: ncc-gradle-vscode ${endColor}"

    ## 创建临时目录
    rm -rf $rootDir/tmp/
    mkdir -p $rootDir/tmp/
    cd $rootDir/tmp/; echo cd `pwd`

    ## 拉取脚手架
    git clone -b main https://gitee.com/mozhuanzuojing/ncc-gradle-vscode.git --depth 1
    echo -e "${headColor} ➩ ${endColor}下载完成"

    ## 优先复制bump.sh
    echo -e "🟡 ##### 正在替换脚本自身【bump.sh】，如果出现语法错误，请重新执行！"
    cp -v $rootDir/tmp/ncc-gradle-vscode/am/bump.sh $rootDir
    sleep 0.2


    ## 拷贝
    cd $rootDir/tmp/ncc-gradle-vscode; echo cd `pwd`

    echo -e "${headColor} ➩ ${endColor}正在拷贝/gradle ..."
    rm -rf $rootDir/gradle
    cp -r am/gradle $rootDir

    echo -e "${headColor} ➩ ${endColor}正在拷贝/arthas ..."
    rm -rf $rootDir/arthas
    cp -r am/arthas $rootDir

    echo -e "${headColor} ➩ ${endColor}正在拷贝/buildSrc ..."
    rm -rf $rootDir/buildSrc
    cp -r am/buildSrc $rootDir

    echo -e "${headColor} ➩ ${endColor}正在拷贝/.vscode ..."
    cp -f am/.vscode/tasks.json $rootDir/.vscode
    cp -f am/.vscode/extensions.json $rootDir/.vscode

    echo -e "${headColor} ➩ ${endColor}正在拷贝根目录下的文件 ..."
    rm -f $rootDir/*.jar
    cp -f am/*.jar $rootDir
    cp -f am/*.gradle $rootDir
    cp -f -p -r am/gradlew* $rootDir
    cp -f am/nccmain* $rootDir
    cp -f am/.editorconfig $rootDir
    cp -f am/.gitattributes $rootDir
    cp -f --update=none am/ocean-git.sh $rootDir
    cp -f am/ocean.sh $rootDir
    cp -f am/README.md $rootDir
    cp -f CHANGELOG.md $rootDir

    ## 动态更新文件
    if grep -q "org.gradle.java.home" "$rootDir/gradle.properties"; then
        echo -e "${headColor} ➩ ${endColor} 开始更新 gradle.properties、launch.json ..."
        cp -f am/.vscode/launch.json $rootDir/.vscode
        cp -f -p -r am/gradle.properties $rootDir
    else
        echo -e "${headColor} ➩ ${endColor} gradle.properties 检查通过"
    fi
else
	echo -e "${headColor} ➩ ${endColor}跳过拉取脚手架【ncc-gradle-vscode】"
fi



# 回到工作目录 -- 拷贝完成
cd $rootDir; echo cd `pwd`



# 二、更新JDK配置
## 检查JDK环境变量
if [ ! -d "$JDK17" ]; then
	echo -e "${headColor}☯ 环境变量【JDK17】不存在，请确认后重启vscode，刷新环境变量缓存 ${endColor}"
    exit 4
fi
if [ ! -d "$JDK25" ]; then
	echo -e "${headColor}☯ 环境变量【JDK25】不存在，请确认后重启vscode，刷新环境变量缓存 ${endColor}"
    exit 5
fi


## 确保JDK软链接存在
lib64_jvm="/usr/lib64/jvm"
if [ ! -d $lib64_jvm ]; then
    echo -e "${headColor}☯ 正在创建【$lib64_jvm】，请输入用户密码 ${endColor}"
    sudo mkdir -p $lib64_jvm
    if [ $? != 0 ]
	then 
		exit 6
	fi
fi



## jdk17软链接
lib64_jdk17="$lib64_jvm/jdk17"
if [ ! -h "$lib64_jdk17" ]; then
    echo -e "${headColor}☯ 正在创建软链接【$lib64_jdk17】 ${endColor}"
    sudo ln -s $JDK17 $lib64_jdk17
elif [ ! -e "$lib64_jdk17" ]; then
    echo -e "${headColor}☯ 软链接已失效，正在重建软链接【$lib64_jdk17】 ${endColor}"
    sudo rm $lib64_jdk17
    sudo ln -s $JDK17 $lib64_jdk17
fi
    if [ $? != 0 ]
	then 
		exit 8
	fi

## jdk25软链接
lib64_jdk25="$lib64_jvm/jdk25"
if [ ! -h "$lib64_jdk25" ]; then
    echo -e "${headColor}☯ 正在创建软链接【$lib64_jdk25】 ${endColor}"
    sudo ln -s $jdk25 $lib64_jdk25
elif [ ! -e "$lib64_jdk25" ]; then
    echo -e "${headColor}☯ 软链接已失效，正在重建软链接【$lib64_jdk25】 ${endColor}"
    sudo rm $lib64_jdk25
    sudo ln -s $jdk25 $lib64_jdk25
fi
    if [ $? != 0 ]
	then 
		exit 9
	fi


# sed兼容mac
sedPrefix="sed -i "
if [ "$(uname)" == "Darwin" ]; then
	echo "This is a Mac."
	sedPrefix="sed -i '' "
fi


## 打开启动检测JVM
$sedPrefix 's!^.*org\.gradle\.java\.installations\.auto-detect.*!org.gradle.java.installations.auto-detect=true!' $rootDir/gradle.properties
## $sedPrefix 's!services\.gradle\.org/distributions!mirrors.cloud.tencent.com/gradle!' $rootDir/gradle/wrapper/gradle-wrapper.properties



# 三、是否更新配置HOME -- 全新盘
echo -n -e "${headColor}▶ 是否切换HOME目录? (Y/n) ${endColor}"
read updateHomeDir
if [ "$updateHomeDir" == "Y" ] || [ "$updateHomeDir" == "y" ]
then
	## 开始配置HOME
    echo -n -e "${headColor}▶ 请输入HOME目录: ${endColor}"
    while read homeDir
    do
    ## 如果文件夹不存在
    if [ ! -d "$homeDir/modules" ]
    then
        echo -e "${headColor} ➩ ${endColor}HOME目录不正确！请重新输入:"
    else
        ## 获取原始的HOME，保留補丁目錄：classes
        oldHome=`awk '{ if (index($0,"FIELD_NC_HOME")) { print $0}}' ./.vscode/settings.json | awk -F\" '{print $4}'`
        if [ "$oldHome" != "$homeDir" ]
        then
            if [ -d "$oldHome/classes" ]
            then
                echo -e "${headColor} ➩ ${endColor}更新补丁[$homeDir/classes] ..."
                cp -rf $oldHome/classes $homeDir

                # 同步eclipseSerializer、h2依赖包
                cp -rf $oldHome/lib/eclipseSerializer*.jar $homeDir/lib/
                cp -rf $oldHome/lib/h2*.jar $homeDir/lib/
            fi

            echo -e "${headColor} ➩ ${endColor}同步驱动、数据源[$oldHome -> $homeDir]  ..."
            cp -f -p -r -u $oldHome/driver $homeDir
            cp -f -p $oldHome/ierp/bin/prop.xml $homeDir/ierp/bin/
            # 同步文件服务器配置
            cp -f -p $oldHome/ierp/sf/ufsconfig/ufs.properties $homeDir/ierp/sf/ufsconfig/
            # cp -i -p $oldHome/ierp/bin/dbdriverset.xml $homeDir/ierp/bin
        fi

        ## 添加执行权限
        chmod -R +x $homeDir/ant $homeDir/bin $homeDir/intelliv

        ## 更新新HOME
        echo -e "${headColor} ➩ ${endColor}更新.vscode/settings.json ..."
        $sedPrefix 's!^.*FIELD_NC_HOME.*!    "FIELD_NC_HOME": "'$homeDir'",!' ./.vscode/settings.json
        ## 获取当前的HOME
        currentHome=`awk '{ if (index($0,"FIELD_NC_HOME")) { print $0}}' ./.vscode/settings.json | awk -F\" '{print $4}'`
        echo -e "${headColor} ➩ ${endColor}当前HOME目录："$currentHome

        ## 更新报文配置
        echo -e "${headColor} ➩ ${endColor}更新报文配置 ..."
        $sedPrefix 's!<gzip>true</gzip>!<gzip>false</gzip>!' $currentHome/hotwebs/nccloud/WEB-INF/config/miscellaneous.xml
        $sedPrefix 's!<mark>true</mark>!<mark>false</mark>!' $currentHome/hotwebs/nccloud/WEB-INF/config/miscellaneous.xml
        $sedPrefix 's!<aesKey>true</aesKey>!<aesKey>false</aesKey>!' $currentHome/hotwebs/nccloud/WEB-INF/config/miscellaneous.xml
        break
    fi
    done
else
	echo -e "${headColor} ➩ ${endColor}跳过更新HOME目录"
fi


# 三、清理所有 -- 更新HOME强制更新类路径
if [ "$updateHomeDir" == "Y" ] || [ "$updateHomeDir" == "y" ]
then
    cleanAll="Y"
else 
    echo -n -e "${headColor}▶ 是否更新类路径? (Y/n) ${endColor}"
    read cleanAll
fi

if [ "$cleanAll" == "Y" ] || [ "$cleanAll" == "y" ]
then
	echo -e "${headColor} ➩ ${endColor}正在删除和更新构建文件 ..."
    
    ## delete
    echo -e "${headColor} ➩ ${endColor} 删除各模块下的 build.gradle ..."
    rm $rootDir/subprojects/*/build.gradle
    echo -e "${headColor} ➩ ${endColor} 删除各模块下的 bin/build ..."
    rm -rf $rootDir/subprojects/*/bin
    rm -rf $rootDir/subprojects/*/build


    ## 如果脚手架已经下载完成则覆盖预置模块
    if [ -d "$rootDir/tmp/ncc-gradle-vscode/am/subprojects" ]; then
        ### 删除虚拟模块 nccmain、nccweb
        rm -rf $rootDir/subprojects/nccmain
        rm -rf $rootDir/subprojects/nccweb
        ## 拷贝虚拟模块 nccmain、nccweb
        cp -r $rootDir/tmp/ncc-gradle-vscode/am/subprojects/* $rootDir/subprojects/
    fi

    ## 拷贝预置脚本
    cp $rootDir/subprojects/nccmain/META-INF/build.gradle $rootDir/subprojects/nccmain/
    cp $rootDir/subprojects/nccweb/META-INF/build.gradle $rootDir/subprojects/nccweb/
    echo -e "${headColor} ➩ ${endColor} nccmain、nccweb的脚本预置完成 ..."

    ## 开始自动扫描
    echo -e "${headColor} ➩ ${endColor}开始自动扫描依赖 ..."

    ## 回到根目录
    cd $rootDir
    echo `pwd`

    ## 授权
    chmod +x gradle*

    ## Refresh Gradle Projects View
    echo -e "${headColor} ➩ ${endColor}开始刷新Gradle项目 ..."
    # ./gradlew clean -U
    ./gradlew clean

    ## 检查任务完整依赖图
    echo -e "${headColor} ➩ ${endColor}检查任务完整依赖图 ..."
    ./gradlew 'deployAndInitDependencies' -m

    ## 执行初始化模块任务
    echo -e "${headColor} ➩ ${endColor}执行初始化模块任务 ..."
    ./gradlew 'deployAndInitDependencies'
else
	echo -e "${headColor} ➩ ${endColor}跳过刪除build.gradle"
fi



# 四、清理
echo -e "${headColor}▶ 開始清理 ...${endColor}"
## 刪除error.log -- ignore not exist file
rm -f $rootDir/*.log
## 删除临时目录 -- tmp使用结束
rm -rf $rootDir/tmp/



# 授權
chmod +x gradle*
chmod +x *.sh
chmod +x arthas/*



# 结束 -- http://zhongguose.com/#fengyehong -- https://www.emojiall.com/zh-hans/all-emojis?type=normal
greenColor='\033[38;2;183;212;7m'
echo ""
sleep 0.2
echo -e "${greenColor}🟢 更新结束；请执行如下命令：${endColor}"
echo -e "${greenColor} ★ ${endColor}F1 -> Java: Clean Java Language Server Workspace"


sleep 0.2
echo -e "${greenColor}🟢 编译结束；请执行如下命令：${endColor}"
## `Terminal` -> `Run Task...` -> `syncLaunch`
echo -e "${greenColor} ★ ${endColor}ROOT -> Tasks -> ocean sync -> syncLaunch"
## `Terminal` -> `Run Task...` -> `syncLocalConfig`
echo -e "${greenColor} ☆ ${endColor}ROOT -> Tasks -> ocean sync -> syncLocalConfig"

exit 0
